package dev.serbia.tvguide;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class Main_Form extends Activity {
	
	protected static final int SUB_ACTIVITY_REQUEST_CODE = 1337;
	Button btnPrikazi;
	TextView stanje_servera;
	TextView trenutno_na_programu;
	String stanica;
	ProgressDialog myProgressDialog = null;
	private ProgressBar progressBar;
	Boolean ServerOnline;
	
	Handler mHandler = new Handler();
	
    String[] kanali = {
            "rts-1",
            "rts-2",
            "avala",
            "pink",
            "fox",
            "b92",
            "studio-b",
            "discovery"
    };

	final ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, ToneGenerator.MAX_VOLUME);
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Request for the progress bar to be shown in the title
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.main_form);
         
       btnPrikazi = (Button) findViewById(R.id.btnPrikazi);
       stanje_servera = (TextView) findViewById(R.id.stanje_servera);
       trenutno_na_programu = (TextView) findViewById(R.id.trenutno_na_programu);
       progressBar = (ProgressBar) findViewById(R.id.progress_small);
       btnPrikazi.setOnClickListener(new View.OnClickListener() 
       {
           public void onClick(View v) 
           {            
               Intent ListViewIntent = new Intent(Main_Form.this, ListView_Form.class);
               
               Bundle b = new Bundle(); 
               b.putString("stanica", stanica);
               ListViewIntent.putExtras(b); 
               // We use SUB_ACTIVITY_REQUEST_CODE as an 'identifier' 
               startActivityForResult(ListViewIntent, SUB_ACTIVITY_REQUEST_CODE);
               
            //   Main_Form.this.startActivity(ListViewIntent);
       }});
         
         
         final Spinner s = (Spinner) findViewById(R.id.spinner);
         
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        		 android.R.layout.simple_spinner_item, kanali);
         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         
      /*   ArrayAdapter adapter = ArrayAdapter.createFromResource(
                 this, R.array.kanali, android.R.layout.simple_spinner_item);
         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); */
         s.setAdapter(adapter);
         
         s.setOnItemSelectedListener(new OnItemSelectedListener()
         {
             public void onItemSelected(AdapterView<?> arg0, 
             View arg1, int arg2, long arg3) 
             {
                 int index = s.getSelectedItemPosition();
                 stanica = kanali[index];
                 // Request for the progress bar to be shown in the title
              	 progressBar.setVisibility(0);	 
                 trenutno_na_programu.setText("Учитавам...");
                	 new Thread() { 
                         public void run() {
               try
         		{
            	   //setProgressBarVisibility(true);

            	   URL myURL = null;
					try {
						myURL = new URL("http://www.serbiandownload.com/tv/program/lat/?stanica=" + stanica + "&trenutno=1");
					} catch (MalformedURLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
         			URLConnection ucon = null;
					try {
						ucon = myURL.openConnection();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					InputStream is = null;
					try {
						is = ucon.getInputStream();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					BufferedInputStream bis = new BufferedInputStream(is);
         			final ByteArrayBuffer baf = new ByteArrayBuffer(50);
         			int current = 0;
             		
         			try {
						while((current = bis.read()) != -1)
							{
								baf.append((byte)current);
							}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
            	   	mHandler.post(new Runnable() {
         				public void run() { 
            	   		
         			// Convert the Bytes read to a String.
         			String myString = new String(baf.toByteArray());
         			
         			if (myString.length() > 1) {
         			trenutno_na_programu.setText("Тренутно на програму:\n\n" + myString);
         			progressBar.setVisibility(8);}
         			}});
         		} catch (Exception e)
     			{
     				//myString = e.getMessage();
     			}}}.start(); //NewThread se završava ovde ..
             }
             
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}   	
         });
}
    
    @Override
    protected void onResume(){
    	super.onResume();
    	final Handler mHandler = new Handler();
    	
    	getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
                Window.PROGRESS_VISIBILITY_ON);
    	
    	mHandler.post(new Runnable() {
            public void run() { 
            		stanje_servera.setText("Стање сервера?");
            		stanje_servera.setTextColor(Color.GRAY);
            	//	btnPrikazi.setClickable(false);
            	 }});
        //------------------------ IS ONLINE --------------------------------  
        new Thread() { 
            public void run() { 
                 try{ 
                 	
                 	URL url = new URL("http://www.serbiandownload.com");

                     HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                     urlc.setRequestProperty("User-Agent", "TV Vodic Android");
                     urlc.setRequestProperty("Connection", "close");
                     urlc.setConnectTimeout(1000 * 10); // mTimeout is in seconds
                             urlc.connect();
                             
                             if (urlc.getResponseCode() == 200) {
                                 ServerOnline = true;
                             } else ServerOnline = false;
                             
                             mHandler.post(new Runnable() {
                                 public void run() { 
                                 		stanje_servera.setText("ТВ Водич је повезан");
                                 		stanje_servera.setTextColor(Color.GREEN);
                                 		btnPrikazi.setClickable(true);
                                 		
                                        getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
                                                Window.PROGRESS_VISIBILITY_OFF);  
                                 	 }});
                             
                 } catch (Exception e) { toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP);
                 Log.v("MP error",e.toString());	
                 
                 mHandler.post(new Runnable() {
                     public void run() { 
                    	 	stanje_servera.setText("Сервер није доступан, провери везу ка интернету!");
                    	 	stanje_servera.setTextColor(Color.RED);
                     	//	btnPrikazi.setClickable(false);
                            getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
                                    Window.PROGRESS_VISIBILITY_OFF);
                     	 }});
                 } 
            } 
       }.start();
     //------------------------ IS ONLINE -------------------------------- KRAJ  	
    }
}
